<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  ~   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  --%>

<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<html>
<head>
    <title>新建集群</title>
    <script>

        $(function () {

            $(":input").inputmask();


            var clusterConfigForm = $('#new-cluster-config-form');
            var isPersist = clusterConfigForm.find("input[name='isPersist']");
            var persistConfigPanel = clusterConfigForm.find("#persistConfigPanel");
            var appendOnlyYes = clusterConfigForm.find("input[id='appendOnlyYes']");
            var appendOnlyNo = clusterConfigForm.find("input[id='appendOnlyNo']");
            var appendOnlyNoSeconds = clusterConfigForm.find("input[id='appendOnlyNoSeconds']");
            var appendOnlyNoKeys = clusterConfigForm.find("input[id='appendOnlyNoKeys']");
            isPersist.bind('click', function(){
                if ($(this).prop('checked')){
                    persistConfigPanel.removeAttr("style");
                    appendOnlyYes.removeProp('disabled').prop('checked','checked');
                    appendOnlyNo.removeProp('disabled');
                }else{
                    persistConfigPanel.css('background-color','#F6F6F6');
                    appendOnlyYes.removeProp('checked').prop('disabled','disabled');
                    appendOnlyNo.removeProp('checked').prop('disabled','disabled');
                    appendOnlyNoSeconds.prop('disabled','disabled');
                    appendOnlyNoKeys.prop('disabled','disabled');
                }
            });
            appendOnlyYes.bind('click', function(){
                appendOnlyNoSeconds.prop('disabled','disabled');
                appendOnlyNoKeys.prop('disabled','disabled');
            });
            appendOnlyNo.bind('click', function(){
                appendOnlyNoSeconds.removeProp('disabled');
                appendOnlyNoKeys.removeProp('disabled');
            });
            //console.info(clusterConfigForm.find("input[name='isPersist']").attr('checked'));

            $.validator.addMethod("host", function(value, element) {
                var length = value.length;
                var attr = $(element).attr("isSetSelectValue");
                return attr=="true";
                //return this.optional(element) || (attr);
            }, "从下拉框选择");


            $("#create-cluster").click(function () {
                var form = $("#new-cluster-form");
                if (!form.valid()){
                    toastr.warning("集群配置输入不完整！");
                    return;
                }
                if (nodeTable == null){
                    toastr.warning("节点尚未配置，请先创建主从节点！");
                    return;
                }
                form = $("#nodes-form");
                if (!$("#nodes-form").valid()){
                    toastr.warning("节点配置输入不完整，不能保存！");
                    return;
                }
                var nodesName = nodeTable.bootstrapTable('getData');
                var masters = [];
                for (var i = 0; i < nodesName.length; i++){
                //for (var i in nodesName){
                    var nodeName = nodesName[i];
                    var masterNode = nodeName.masterNode;
                    //console.info(form.find("input#"+masterNode).attr('data-id') + "  " + form.find("input#"+masterNode+"-port").val());
                    var master = {hostId: form.find("input#"+masterNode).attr('data-id'), port: form.find("input#"+masterNode+"-port").val()};
                    var slaveNodes = nodeName.slaveNode;
                    var slaves = [];
                    for (var j = 0; j < slaveNodes.length; j++){
                    //for (var j in slaveNodes){
                        var slaveNode = slaveNodes[j];
                        //console.info("     " + form.find("input#"+slaveNode).attr('data-id') + "  " + form.find("input#"+slaveNode+"-port").val());
                        slaves.push({hostId: form.find("input#"+slaveNode).attr('data-id'), port: form.find("input#"+slaveNode+"-port").val()})
                    }
                    master.slaveNodes = slaves;
                    masters.push(master);
                }
                if (checkNodesInputDuplicate(masters)){
                    toastr.warning("节点配置输入有重复，请检查！");
                    return;
                }
                var param = {clusterName: $('#clusterName').val(), clusterNodeConfig:{}};
                param.masterNodes = masters;

                var nodeConfig = {};
                var maxMemory = clusterConfigForm.find("input[name='maxMemory']");
                if (maxMemory.val() != ""){
                    nodeConfig.maxMemory = maxMemory.val();
                }
                if (isPersist.prop('checked')){
                    if (appendOnlyYes.prop('checked')){
                        nodeConfig.appendOnly = appendOnlyYes.val();
                    }else{
                        nodeConfig.appendOnly = appendOnlyNo.val();
                        nodeConfig.appendOnlyNoSeconds = appendOnlyNoSeconds.val();
                        nodeConfig.appendOnlyNoKeys = appendOnlyNoKeys.val();
                        if (nodeConfig.appendOnlyNoSeconds == "" || nodeConfig.appendOnlyNoKeys == ""){
                            toastr.warning("集群节点参数配置不完整，请检查！");
                            return;
                        }
                    }
                }
                param.clusterNodeConfig = nodeConfig;
                //$.post("${ctx}/redis-api/newCluster", param, function(data) {
                //    toastr.info("新建集群成功！");
                //}, "json");
                $.ajax({
                    url: "${ctx}/redis-api/newCluster",
                    type : 'POST',
                    data: $.toJSON(param),
                    contentType : 'application/json; charset=utf-8',
                    dataType: 'json',
                    success : function(data, status, xhr) {
                        if (data.success){
                            toastr.success("新建集群成功！", "", {timeOut:0});
                        }
                    }
                });

            });
            $("#new-nodes").click(function () {
                $("#new-nodes-form").validate({
                    submitHandler: function(form) {
                        var masterNum = $("#masterNum").val();
                        var slaveNum = $("#slaveNum").val();
                        var nodesNameData = [];

                        for (var i = 0; i < masterNum; i++){
                            var masterNode = 'masterNode-'+i;
                            var slaveNodes = [];
                            for (var j = 0; j < slaveNum; j++){
                                slaveNodes.push('slaveNode-'+i+"-"+j);
                            }
                            var masterSlaveNodes = {id:i, masterNode:masterNode, slaveNode:slaveNodes};
                            nodesNameData.push(masterSlaveNodes);
                        }

                        $.post("${ctx}/redis-api/getHosts", {offset:0,limit:999}, function(data) {
                            var hostData = {value:data.rows};
                            createNodeTable(nodesNameData);
                            for (var i = 0; i < nodesNameData.length; i++){
                            //for (var i in nodesNameData){
                                var masterSlaveNodes = nodesNameData[i];
                                initDropDownComponent(masterSlaveNodes.masterNode, hostData);
                                var slaveNodes = masterSlaveNodes.slaveNode;
                                for (var j = 0; j < masterSlaveNodes.slaveNode.length; j++){
                                //for (var j in masterSlaveNodes.slaveNode){
                                    initDropDownComponent(masterSlaveNodes.slaveNode[j], hostData);
                                }
                            }
                            $(":input").inputmask();
                        });

                    }
                });

            });

        });

        var nodeTable = null;
        function createNodeTable(data){
            if (nodeTable != null){
                nodeTable.bootstrapTable('load', data);
                return;
            }
            nodeTable = $('#nodes-table').bootstrapTable({
                uniqueId: "id",
                classes: "table table-hover table-no-bordered",
                striped: false,
                singleSelect: false,
                data: data,
                locale: "zh-US" ,
                columns: [{
                    title: '主节点',
                    field: 'masterNode',
                    align: 'center',
                    valign: 'middle',
                    width: '45%',
                    formatter:function(value, row, index){
                        return getNodeHtml(value);
                    }
                },{
                    title: '',
                    field: 'id',
                    align: 'center',
                    valign: 'middle',
                    width: '10%',
                    formatter:function(value, row, index){
                        return "<span class='glyphicon glyphicon-arrow-left' style='display:block; margin-top: -15px'></span>";
                    }
                }, {
                    title: '从节点',
                    field: 'slaveNode',
                    align: 'center',
                    valign: 'middle',
                    width: '45%',
                    formatter:function(value, row, index){
                        var html = "";
                        if (value.length > 0){
                            for (var i = 0; i < value.length; i++){
                            //for (var i in value){
                                html += getNodeHtml(value[i]);
                            }
                        }
                        return html;
                    }
                }]
            });
            nodeTable.data('bootstrap.table').$tableBody.css('overflow','visible');

        }

        function checkNodesInputDuplicate(masterNodes){
            var data = [];
            for (var i = 0; i < masterNodes.length; i++){
            //for (var i in masterNodes){
                var masterNode = masterNodes[i];
                data.push(masterNode.hostId + ":" + masterNode.port);
                var slaveNodes = masterNode.slaveNodes;
                for (var j = 0; j < slaveNodes.length; j++) {
                //for (var j in slaveNodes) {
                    var slaveNode = slaveNodes[j];
                    data.push(slaveNode.hostId + ":" + slaveNode.port);
                }
            }
            var nary=data.sort();
            for(var i=0;i<nary.length;i++){
                if (nary[i]==nary[i+1]){
                    return true;
                }
            }
            return false;
        }

        function initDropDownComponent(id, hostData){
            //var hostData={value:[{id:1,ip:'10.10.10.1'},{id:2,ip:'10.10.10.2'},{id:3,ip:'10.10.10.3'},{id:4,ip:'10.10.10.4'},{id:5,ip:'10.10.10.5'}]};
            $("input#"+id).bsSuggest({
                //url: "../data.json",
                data: hostData,
                idField: "id",
                keyField: "ip",
                effectiveFields:["id","ip"],
                //effectiveFieldsAlias:["ID","IP地址"],
                showHeader:false,
                autoDropup: true
            }).on('onSetSelectValue', function (e, keyword, data) {
                //console.log('onSetSelectValue: ', keyword, data);
                $(this).attr("isSetSelectValue",true);
            }).on('onUnsetSelectValue', function (e, keyword, data) {
                //console.log('onSetSelectValue: ', keyword, data);
                $(this).attr("isSetSelectValue",false);
            });
        }

        function getNodeHtml(nodeId){
            var html =
                    '<div class="form-group">'+
                    '    <label class="col-md-2 control-label" for="'+nodeId+'">主机</label>'+
                    '    <div class="col-md-5">'+
                    getDropDownHostHtml(nodeId)+
                    '    </div>'+
                    '    <label class="col-md-2 control-label" for="'+nodeId+'-port">端口</label>'+
                    '    <div class="col-md-3">'+
                    '        <input class="form-control" id="'+nodeId+'-port" name="'+nodeId+'-port" type="text" placeholder="" required="true" min="1" digits="true" data-inputmask="\'alias\': \'decimal\'"/>'+
                    '    </div>'+
                    '</div>';
            return html;
        }

        function getDropDownHostHtml(nodeId){
            var html =
                    '<div class="input-group">'+
                    '    <input type="text" class="form-control" id="'+nodeId+'" name="'+nodeId+'" host="true">'+
                    '    <div class="input-group-btn" style="vertical-align: top">'+
                    '        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">'+
                    '            <span class="caret"></span>'+
                    '        </button>'+
                    '        <ul class="dropdown-menu dropdown-menu-right" role="menu"></ul>'+
                    '    </div>'+
                    '</div>';
            return html;
        }

        function getDropDownOperHtml(value){
            var html = '<div class="dropdown">'+
                    '  <button class="btn btn-info dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">'+
                    '选择操作'+
                    '  <span class="caret"></span>'+
                    '  </button>'+
                    '  <ul class="dropdown-menu dropdown-menu-right">'+
                    '    <li><a href="#">添加从节点</a></li>'+
                    '    <li><a href="#">删除从节点</a></li>'+
                    '    <li><a href="javascript:removeMasterSlaveNodes('+value+')">删除主从节点</a></li>'+
                    '  </ul>'+
                    '</div>';
            return html;
        }

        function removeMasterSlaveNodes(id){
            $('#nodes-table').bootstrapTable('removeByUniqueId',id);
        }

    </script>
</head>

<body>

<div class="page-title">
    <h3>新建集群</h3>
</div>




<div class="row">
<div class="col-md-12 widget-container fluid-height clearfix">
    <form class="form-horizontal" id="new-cluster-form">
        <div class="heading">
            <i class="icon-group"></i>集群配置
        </div>
        <div class="widget-content padded clearfix">
            <div class="form-group">
                <label for="clusterName" class="col-md-2 control-label">集群名称</label>
                <div class="col-md-8">
                    <input class="form-control" id="clusterName" type="text" placeholder="" required/>

                </div>
            </div>
        </div>
    </form>
    <form class="form-horizontal" id="new-cluster-config-form">
        <div class="heading">
            <i class="icon-group"></i>集群节点参数配置
        </div>
        <div class="widget-content padded clearfix">

            <div class="form-group">
                <label class="control-label col-md-2" for="isPersist">持久化配置</label>
                <div class="col-md-3">
                    <label class="checkbox"><input type="checkbox" id="isPersist" name="isPersist"><span>需要持久化</span></label>
                </div>
                <label class="col-md-2 control-label" for="maxMemory">最大使用内存</label>
                <div class="col-md-3">
                    <div class="input-group">
                        <input class="form-control" id="maxMemory" name="maxMemory" type="text" placeholder="内存不限制为空" data-inputmask="'alias': 'decimal'"/>
                        <span class="input-group-addon">M</span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-2"></label>
                <div class="col-md-5" style="background-color: #F6F6F6" id="persistConfigPanel">
                    <label class="radio"><input id="appendOnlyYes" name="appendOnly" type="radio" value="yes" disabled><span>AOF方式</span></label>
                    <label class="radio"><input id="appendOnlyNo" name="appendOnly" type="radio" value="no" disabled><span>RDB方式</span></label>
                    <div class="col-md-2">
                        <input class="form-control" id="appendOnlyNoSeconds" name="appendOnlyNoSeconds" type="text" min="1" digits="true" data-inputmask="'alias': 'decimal'" disabled />
                    </div>
                    <label class="col-md-2 control-label" style="text-align:left">秒内超过</label>
                    <div class="col-md-2">
                        <input class="form-control" id="appendOnlyNoKeys" name="appendOnlyNoKeys" type="text" min="1" digits="true" data-inputmask="'alias': 'decimal'" disabled />
                    </div>
                    <label class="col-md-6 control-label" style="text-align:left">个key被修改则发起快照保存</label>
                </div>
            </div>
        </div>
    </form>
    <div class="form-horizontal">
        <div class="heading">
            <i class="icon-group"></i>节点配置
        </div>
        <div class="widget-content padded clearfix">
            <form class="form-group" id="new-nodes-form">
                <label class="col-md-2 control-label" for="masterNum">分配的主节点个数</label>
                <div class="col-md-2">
                    <input class="form-control" id="masterNum" name="masterNum" type="text" placeholder="" required="true" min="3" digits="true" data-inputmask="'alias': 'decimal'" />
                </div>
                <label class="col-md-3 control-label" for="slaveNum">每个主节点分配的从节点个数</label>
                <div class="col-md-2">
                    <input class="form-control" id="slaveNum" name="slaveNum" type="text" placeholder="" required="true" min="1" digits="true" data-inputmask="'alias': 'decimal'"/>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-default" id="new-nodes">创建主从节点</button>
                </div>
            </form>
            <form id="nodes-form">
                <table id="nodes-table"></table>
            </form>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="create-cluster">开始新建集群</button>
    </div>
</div>
</div>
</body>
</html>
